package com.sky.service.impl;


import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.Result;
import com.sky.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    /**
     *新增菜品和口味，意味着不同数据库表的相应处理，所以对于事务的管理就有要求，需要进行事务管理。
     * @param dishDTO
     */
    @Transactional
    public void addDishWithFlavor(DishDTO dishDTO) {

        Dish dish = Dish.builder().build();
        BeanUtils.copyProperties(dishDTO, dish);
        // 向菜品中增加一条数据
        dishMapper.insert(dish);
        Long dishId = dish.getId();
        // 向口味表插入一条或者多条数据

        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> {flavor.setDishId(dishId);});
            // SQL支持集合插入
            dishFlavorMapper.insertBatch(flavors);
        }



    }
}
